<template>
  <div>
    <!-- 视频上传 -->
    <el-upload
      class="upload-demo"
      drag
      action="#"
      :on-change="handleChange"
      :before-upload="handleBeforeUpload"
      v-if="showVideo"
    >
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <!-- 上传进度条 -->
    <el-progress
      v-if="showProgress"
      :percentage="uploadPercentage"
      class="progess"
    ></el-progress>

    <!-- 上传完成后的视频显示 -->
    <div v-if="videoUrl" class="video-container">
      <video
        ref="uploadedVideo"
        @timeupdate="updateProgress"
        @volumechange="updateVolume"
        @play="startCount"
      >
        <source :src="videoUrl" type="video/mp4" />
        Your browser does not support the video tag.
      </video>

      

      <!-- 原生视频控制 -->
      <div class="video-controls">
        <button @click="playPause"  class="">
          {{ isPlaying ? "暂停" : "播放" }}
        </button>
        <input
          type="range"
          min="0"
          max="100"
          v-model="currentProgress"
          @input="seekTo($event.target.value)"
        />
        <button @click="toggleMute">
          {{ isMuted ? "取消静音" : "静音" }}
        </button>
        <input
          type="range"
          min="0"
          max="100"
          v-model="currentVolume"
          @input="setVolume"
        />
      </div>
      <!-- 视频下方PV次数统计 -->
      <div class="pv-count">PV次数：{{ pvCount }}</div>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
import { ElUpload, ElIcon, ElProgress } from "element-plus";
import SparkMD5 from "spark-md5";

export default {
  components: {
    ElUpload,
    ElIcon,
    ElProgress,
  },
  setup() {
    const uploadedVideo = ref(null);
    let prevVolume = 100; // 默认音量为最大值（100）
    const showProgress = ref(false);
    const showVideo = ref(true);
    const uploadPercentage = ref(0);
    const videoUrl = ref("");
    const isPlaying = ref(false);
    const currentProgress = ref(0);
    const isMuted = ref(false);
    const currentVolume = ref(100);
    const pvCount = ref(0); // PV次数，默认值为0
    let playStartTime = 0; // 记录播放开始时间的时间戳

    // Methods
    // 更新播放进度
    const updateProgress = () => {
      const video = uploadedVideo.value;
      const currentTime = video.currentTime;
      const duration = video.duration;
      currentProgress.value = (currentTime / duration) * 100;
    };

    // 更新音量控制
    const updateVolume = () => {
      const video = uploadedVideo.value;
      currentVolume.value = video.muted ? 0 : video.volume * 100;
    };

    // 计算文件hash值
    const calculateFileHash = (file) => {
      return new Promise((resolve, reject) => {
        const blobSlice =
          File.prototype.slice ||
          File.prototype.mozSlice ||
          File.prototype.webkitSlice;
        const chunkSize = 2 * 1024 * 1024; // 切片大小为2MB

        const chunks = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        const spark = new SparkMD5.ArrayBuffer();

        const fileReader = new FileReader();

        fileReader.onload = function (e) {
          spark.append(e.target.result);
          currentChunk++;

          if (currentChunk < chunks) {
            loadNext();
          } else {
            resolve(spark.end());
          }
        };

        fileReader.onerror = function () {
          reject("Error reading the file.");
        };

        function loadNext() {
          const start = currentChunk * chunkSize;
          const end =
            start + chunkSize >= file.size ? file.size : start + chunkSize;

          fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        }

        loadNext();
      });
    };
    // 切片上传文件
    const handleBeforeUpload = async (file) => {
      showProgress.value = true;

      try {
        // 计算文件哈希值
        const fileHash = await calculateFileHash(file);

        // 将文件哈希值传递给后端，后端根据哈希值判断是否已经上传过相同文件的切片

        // 模拟上传切片过程
        const totalChunks = 5; // 模拟文件分成5片
        let currentChunk = 0;

        const timer = setInterval(() => {
          if (currentChunk < totalChunks) {
            uploadPercentage.value = ((currentChunk + 1) / totalChunks) * 100;
            currentChunk++;
          } else {
            clearInterval(timer);
            showProgress.value = false;
            // 当进度条加载完成的时候，不再显示上传视频的组件
            showVideo.value = false;
            uploadPercentage.value = 0;

            // 上传完成后，设置视频URL并自动播放
            videoUrl.value = URL.createObjectURL(file);
            uploadedVideo.value.load();
            uploadedVideo.value.play();
          }
        }, 1000);
      } catch (error) {
        console.error("Error calculating file hash:", error);
        showProgress.value = false;
        uploadPercentage.value = 0;
      }

      return false; // 阻止默认上传行为
    };

    const handleChange = (fileList) => {
      // 上传成功后，fileList会返回上传成功的文件对象
      // 在这里可以处理上传成功后的逻辑，如保存视频URL等
    };

    // 播放/暂停切换
    const playPause = () => {
      const video = uploadedVideo.value;
      if (isPlaying.value) {
        video.pause();
      } else {
        video.play();
      }
      isPlaying.value = !isPlaying.value;
    };

    // 跳转进度
    const seekTo = (value) => {
      const video = uploadedVideo.value;
      const duration = video.duration;
      const currentTime = (value * duration) / 100;
      video.currentTime = currentTime;
    };

    // 音量控制
    const toggleMute = () => {
      const video = uploadedVideo.value;
      if (isMuted.value) {
        video.muted = false;
        setVolume(prevVolume); // 取消静音后恢复音量到之前保存的值
      } else {
        prevVolume = currentVolume.value; // 保存当前音量进度
        video.muted = true;
      }
      isMuted.value = !isMuted.value;
    };

    // 设置音量
    const setVolume = (value) => {
      const video = uploadedVideo.value;
      video.volume = value / 100;
      currentVolume.value = value;
    };

    // 开始计数
    const startCount = () => {
      const video = uploadedVideo.value;
      if (!video.paused) {
        // 视频正在播放
        playStartTime = new Date().getTime(); // 记录播放开始时间的时间戳
        const interval = setInterval(() => {
          const currentTime = new Date().getTime();
          if (!video.paused && currentTime - playStartTime >= 3000) {
            // 播放超过3秒，PV次数加1
            pvCount.value++;
            clearInterval(interval);
          }
        }, 16);
      }
    };

    return {
      uploadedVideo,
      showProgress,
      showVideo,
      uploadPercentage,
      videoUrl,
      handleBeforeUpload,
      handleChange,
      isPlaying,
      currentProgress,
      isMuted,
      currentVolume,
      playPause,
      seekTo,
      toggleMute,
      setVolume,
      updateProgress,
      updateVolume,
      pvCount,
      startCount,
    };
  },
};
</script>

<style>
.upload-demo {
  border: 1px dashed #f72516;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  color: #999;
  cursor: pointer;
  width: 400px;
  margin-left: 20px;
  margin-top: 20px;
  overflow: hidden;
}

.upload-demo i {
  font-size: 28px;
  /* color: #409eff; */
  margin-bottom: 10px;
}

.upload-demo em {
  color: #666;
}

.video-container {
  position: relative;
  margin-left: 20px;
  margin-top: 10px;
}

.video-controls {
  position: relative;
  bottom: 10px;
  margin: 20px 0;
  width: 500px;
}

.video-controls button {
  margin-left: 20px;
  min-width: 55px;
  min-height: 10px;
  /* 根据需要调整按钮的最小宽度 */
}


.video-controls button,
.video-controls input[type="range"] {
  margin-right: 5px;
}

.pv-count {
  text-align: center;
  margin-top: -14px;
  margin-left: 2px;
  float: left;
}
.progess {
  margin-left: 20px;
  width: 500px;
}
input[type="range"]{
  width: 93px;
    height: 10px;
    margin-left: 4px;

}

</style>
